package com.zhou.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhou.dao.UserDao;
import com.zhou.dao.msjDataDao;
import com.zhou.domain.User;
import com.zhou.domain.Msg;
import com.zhou.domain.msjData;
import com.zhou.server.MsgServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MsgServerImpl implements MsgServer {

    @Autowired
    private msjDataDao msjDataDao;

    @Autowired
    private UserDao userDao;

    //查询聊天记录
    @Override
    public List<msjData> getall(String name, String hyname) {
        //查询发送人ID
        LambdaQueryWrapper<User> lqwuser1 = new LambdaQueryWrapper<>();
        lqwuser1.eq(User::getName,name);
        User userfrom = userDao.selectOne(lqwuser1);
        //查询接收人ID
        LambdaQueryWrapper<User> lqwuser2 = new LambdaQueryWrapper<>();
        lqwuser2.eq(User::getName,hyname);
        User userto = userDao.selectOne(lqwuser2);

        LambdaQueryWrapper<msjData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(msjData::getFromid,userfrom.getId()).eq(msjData::getToid,userto.getId()).or().eq(msjData::getFromid,userto.getId()).eq(msjData::getToid,userfrom.getId());
        List<msjData> msjData = msjDataDao.selectList(lqw);
        return msjData;
    }

    //添加消息
    @Override
    public void addmsg(Msg deserialize) {
        //查询发送人ID
        LambdaQueryWrapper<User> lqwuser1 = new LambdaQueryWrapper<>();
        lqwuser1.eq(User::getName,deserialize.getName());
        User userfrom = userDao.selectOne(lqwuser1);
        //查询接收人ID
        LambdaQueryWrapper<User> lqwuser2 = new LambdaQueryWrapper<>();
        lqwuser2.eq(User::getName,deserialize.getHyname());
        User userto = userDao.selectOne(lqwuser2);

        msjData msjData = new msjData();
        msjData.setMsg(deserialize.getName()+": "+deserialize.getMsg());
        msjData.setFromid(userfrom.getId());
        msjData.setToid(userto.getId());

        msjDataDao.insert(msjData);

    }
}
